{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.5"
    },
    "colab": {
      "name": "circuits.ipynb",
      "provenance": [],
      "collapsed_sections": []
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "doUaJJGSAwCO",
        "colab_type": "text"
      },
      "source": [
        "# Circuits\n",
        "\n",
        "## Conceptual Overview\n",
        "\n",
        "The primary representation of quantum programs in Cirq is the `Circuit` class. A `Circuit` is a collection of `Moments`. A `Moment` is a collection of `Operations` that all act during the same abstract time slice. An `Operation` is a some effect that operates on a specific subset of Qubits, the most common type of `Operation` is a `GateOperation`.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "g_TubHnpIyUH",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "!pip install --quiet cirq\n",
        "import cirq"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "77zB_UqkAwCR",
        "colab_type": "text"
      },
      "source": [
        "![Circuits and Moments](https://cirq.readthedocs.io/en/latest/_static/CircuitMomentOperation.png)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uB8cQJ0PAwCT",
        "colab_type": "text"
      },
      "source": [
        "Let's unpack this.\n",
        "\n",
        "At the base of this construction is the notion of a qubit. In Cirq, qubits and other quantum objects are identified by instances of subclasses of the Qid base class. Different subclasses of Qid can be used for different purposes. For example, the qubits that Google’s Xmon devices use are often arranged on the vertices of a square grid. For this, the class GridQubit subclasses Qid. For example, we can create a 3 by 3 grid of qubits using"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "G30Zl1VwAwCU",
        "colab_type": "code",
        "outputId": "a313d019-b98d-4939-95bc-94e2930cac24",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        }
      },
      "source": [
        "import cirq\n",
        "qubits = [cirq.GridQubit(x, y) for x in range(3) for y in range(3)]\n",
        "\n",
        "print(qubits[0])"
      ],
      "execution_count": 20,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0)\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gpi9rwuiAwCZ",
        "colab_type": "text"
      },
      "source": [
        "The next level up is the notion of a `Gate`. A `Gate` represents a physical process that occurs on a `Qubit`. The important property of a `Gate` is that it can be applied to one or more qubits. This can be done via the `Gate.on` method itself or via `()`, and doing this turns the `Gate` into a `GateOperation`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-X_LL4_nAwCa",
        "colab_type": "code",
        "outputId": "1bff5bb8-a907-4f60-b624-1e23977daf52",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        }
      },
      "source": [
        "# This is an Pauli X gate. It is an object instance.\n",
        "x_gate = cirq.X\n",
        "# Applying it to the qubit at location (0, 0) (defined above)\n",
        "# turns it into an operation.\n",
        "x_op = x_gate(qubits[0])\n",
        "\n",
        "print(x_op)"
      ],
      "execution_count": 21,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "X((0, 0))\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0N7X3nmFAwCd",
        "colab_type": "text"
      },
      "source": [
        "A `Moment` is simply a collection of operations, each of which operates on a different set of qubits, and which conceptually represents these operations as occurring during this abstract time slice. The `Moment` structure itself is not required to be related to the actual scheduling of the operations on a quantum computer, or via a simulator, though it can be. For example, here is a `Moment` in which **Pauli** `X` and a `CZ` gate operate on three qubits:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "naO0-nS0AwCe",
        "colab_type": "code",
        "outputId": "aac1f854-68f7-4342-813a-a1925dc64353",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        }
      },
      "source": [
        "cz = cirq.CZ(qubits[0], qubits[1])\n",
        "x = cirq.X(qubits[2])\n",
        "moment = cirq.Moment([x, cz])\n",
        "\n",
        "print(moment)"
      ],
      "execution_count": 22,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "X((0, 2)) and CZ((0, 0), (0, 1))\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8TxICnXCAwCh",
        "colab_type": "text"
      },
      "source": [
        "The above is not the only way one can construct moments, nor even the typical method, but illustrates that a `Moment` is just a collection of operations on disjoint sets of qubits.\n",
        "\n",
        "Finally, at the top level a `Circuit` is an ordered series of `Moment` objects. The first `Moment` in this series contains the first `Operations that will be applied. Here, for example, is a simple circuit made up of two moments:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "W7ToOyp9AwCi",
        "colab_type": "code",
        "outputId": "030ac365-4fa8-4daf-f0f7-3eab2de72c6b",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        }
      },
      "source": [
        "cz01 = cirq.CZ(qubits[0], qubits[1])\n",
        "x2 = cirq.X(qubits[2])\n",
        "cz12 = cirq.CZ(qubits[1], qubits[2])\n",
        "moment0 = cirq.Moment([cz01, x2])\n",
        "moment1 = cirq.Moment([cz12])\n",
        "circuit = cirq.Circuit((moment0, moment1))\n",
        "\n",
        "print(circuit)"
      ],
      "execution_count": 23,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───@───────\n",
            "           │\n",
            "(0, 1): ───@───@───\n",
            "               │\n",
            "(0, 2): ───X───@───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YMXONr0SAwCl",
        "colab_type": "text"
      },
      "source": [
        "Note that the above is one of the many ways to construct a `Circuit`, which illustrates the concept that a `Circuit` is an iterable of `Moment` objects."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "93Wlr_HjAwCm",
        "colab_type": "text"
      },
      "source": [
        "## Constructing circuits\n",
        "\n",
        "Constructing Circuits as a series of `Moment` objects, with each `Moment` being hand-crafted, is tedious. Instead, we provide a variety of different ways to create a `Circuit`.\n",
        "\n",
        "One of the most useful ways to construct a `Circuit` is by appending onto the `Circuit` with the `Circuit.append` method.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "7xtjmYzKAwCn",
        "colab_type": "code",
        "outputId": "7a87884b-4272-491d-92a5-5d9a67d1804a",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        }
      },
      "source": [
        "from cirq.ops import CZ, H\n",
        "q0, q1, q2 = [cirq.GridQubit(i, 0) for i in range(3)]\n",
        "circuit = cirq.Circuit()\n",
        "circuit.append([CZ(q0, q1), H(q2)])\n",
        "\n",
        "print(circuit)"
      ],
      "execution_count": 24,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───@───\n",
            "           │\n",
            "(1, 0): ───@───\n",
            "\n",
            "(2, 0): ───H───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CKuRApDeAwCp",
        "colab_type": "text"
      },
      "source": [
        "This appended a new moment to the qubit, which we can continue to do:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "HO8WYyU9AwCq",
        "colab_type": "code",
        "outputId": "d65f49a0-196d-4323-97cd-84e130246631",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        }
      },
      "source": [
        "circuit.append([H(q0), CZ(q1, q2)])\n",
        "\n",
        "print(circuit)"
      ],
      "execution_count": 25,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───@───H───\n",
            "           │\n",
            "(1, 0): ───@───@───\n",
            "               │\n",
            "(2, 0): ───H───@───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8HNpFd0UAwCs",
        "colab_type": "text"
      },
      "source": [
        "In these two examples, we appended full moments, what happens when we append all of these at once?"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Q3qzMlQmAwCt",
        "colab_type": "code",
        "outputId": "b9356886-2791-4723-ebe6-2f695dbfb501",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        }
      },
      "source": [
        "circuit = cirq.Circuit()\n",
        "circuit.append([CZ(q0, q1), H(q2), H(q0), CZ(q1, q2)])\n",
        "\n",
        "print(circuit)"
      ],
      "execution_count": 26,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───@───H───\n",
            "           │\n",
            "(1, 0): ───@───@───\n",
            "               │\n",
            "(2, 0): ───H───@───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OQX8FTMyAwCw",
        "colab_type": "text"
      },
      "source": [
        "We see that here we have again created two `Moment` objects. How did `Circuit` know how to do this? `Circuit`'s `Circuit.append` method (and its cousin, `Circuit.insert`) both take an argument called the `InsertStrategy`. By default, `InsertStrategy` is `InsertStrategy.NEW_THEN_INLINE`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2t7qgbPkAwCx",
        "colab_type": "text"
      },
      "source": [
        "### InsertStrategies\n",
        "\n",
        "`InsertStrategy` defines how `Operations` are placed in a `Circuit` when requested to be inserted at a given location. Here, a location is identified by the index of the `Moment` (in the `Circuit`) where the insertion is requested to be placed at (in the case of `Circuit.append`, this means inserting at the `Moment`, at an index one greater than the maximum moment index in the `Circuit`). \n",
        "\n",
        "There are four such strategies: `InsertStrategy.EARLIEST`, `InsertStrategy.NEW`, `InsertStrategy.INLINE` and `InsertStrategy.NEW_THEN_INLINE`.\n",
        "\n",
        "`InsertStrategy.EARLIEST` is defined as:\n",
        "\n",
        "*Scans backward from the insert location until a moment with operations touching qubits affected by the operation to insert is found. The operation is added to the moment just after that location.*\n",
        "\n",
        "For example, if we first create an `Operation` in a single moment, and then use `InsertStrategy.EARLIEST`, `Operation` can slide back to this first ` Moment` if there is space:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Hd5IGmQrAwCx",
        "colab_type": "code",
        "outputId": "2fd507cc-f765-4aa3-e3ad-104f8640af12",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        }
      },
      "source": [
        "from cirq.circuits import InsertStrategy\n",
        "circuit = cirq.Circuit()\n",
        "circuit.append([CZ(q0, q1)])\n",
        "circuit.append([H(q0), H(q2)], strategy=InsertStrategy.EARLIEST)\n",
        "\n",
        "print(circuit)"
      ],
      "execution_count": 27,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───@───H───\n",
            "           │\n",
            "(1, 0): ───@───────\n",
            "\n",
            "(2, 0): ───H───────\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BGnlt-kPAwCz",
        "colab_type": "text"
      },
      "source": [
        "After creating the first moment with a `CZ` gate, the second append uses the `InsertStrategy.EARLIEST` strategy. The `H` on `q0` cannot slide back, while the `H` on `q2` can and so ends up in the first `Moment`.\n",
        "\n",
        "Contrast this with the `InsertStrategy.NEW` `InsertStrategy`:\n",
        "\n",
        "*Every operation that is inserted is created in a new moment.*"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Yupv8gQOAwC0",
        "colab_type": "code",
        "outputId": "7b883d6a-8a3f-4035-b8ad-07c756a7e4ba",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        }
      },
      "source": [
        "circuit = cirq.Circuit()\n",
        "circuit.append([H(q0), H(q1), H(q2)], strategy=InsertStrategy.NEW)\n",
        "\n",
        "print(circuit)"
      ],
      "execution_count": 28,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───H───────────\n",
            "\n",
            "(1, 0): ───────H───────\n",
            "\n",
            "(2, 0): ───────────H───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F7ziPs17AwC2",
        "colab_type": "text"
      },
      "source": [
        "Here every operator processed by the append ends up in a new moment. `InsertStrategy.NEW` is most useful when you are inserting a single operation and do not want it to interfere with other `Moments`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ceb0nBxeAwC3",
        "colab_type": "text"
      },
      "source": [
        "Another strategy is `InsertStrategy.INLINE`:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zsbTh2QhAwC4",
        "colab_type": "text"
      },
      "source": [
        "*Attempts to add the operation to insert into the moment just before the desired insert location. But, if there’s already an existing operation affecting any of the qubits touched by the operation to insert, a new moment is created instead.*"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "J3LTjH9-AwC5",
        "colab_type": "code",
        "outputId": "62d3b6e6-162a-4ddd-a9d1-7cfc77e571c9",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        }
      },
      "source": [
        "circuit = cirq.Circuit()\n",
        "circuit.append([CZ(q1, q2)])\n",
        "circuit.append([CZ(q1, q2)])\n",
        "circuit.append([H(q0), H(q1), H(q2)], strategy=InsertStrategy.INLINE)\n",
        "\n",
        "print(circuit)"
      ],
      "execution_count": 29,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───────H───────\n",
            "\n",
            "(1, 0): ───@───@───H───\n",
            "           │   │\n",
            "(2, 0): ───@───@───H───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7iDg6j4fAwC7",
        "colab_type": "text"
      },
      "source": [
        "After two initial `CZ` between the second and third qubit, we try to insert three `H` `Operations`. We see that the `H` on the first qubit is inserted into the previous `Moment`, but the `H` on the second and third qubits cannot be inserted into the previous `Moment`, so a new `Moment` is created.\n",
        "\n",
        "Finally, we turn to the default strategy:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "O-LfqxSWAwC8",
        "colab_type": "text"
      },
      "source": [
        "*Creates a new moment at the desired insert location for the first operation, but then switches to inserting operations according to `InsertStrategy.INLINE`.*"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "LmT3IKEEAwC9",
        "colab_type": "code",
        "outputId": "605745fc-c2ec-4da5-9a03-4d23e382cffe",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        }
      },
      "source": [
        "circuit = cirq.Circuit()\n",
        "circuit.append([H(q0)])\n",
        "circuit.append([CZ(q1,q2), H(q0)], strategy=InsertStrategy.NEW_THEN_INLINE)\n",
        "\n",
        "print(circuit)"
      ],
      "execution_count": 30,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───H───H───\n",
            "\n",
            "(1, 0): ───────@───\n",
            "               │\n",
            "(2, 0): ───────@───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "m2SoYFsFAwC_",
        "colab_type": "text"
      },
      "source": [
        "The first append creates a single moment with an `H` on the first qubit. Then, the append with the `InsertStrategy.NEW_THEN_INLINE` strategy begins by inserting the `CZ` in a new `Moment` (the `InsertStrategy.NEW` in `InsertStrategy.NEW_THEN_INLINE`). Subsequent appending is done `InsertStrategy.INLINE`, so the next `H` on the first qubit is appending in the just created `Moment`."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ij28qJdtAwC_",
        "colab_type": "text"
      },
      "source": [
        "### Patterns for Arguments to Append and Insert\n",
        "\n",
        "In the above examples, we used a series of `Circuit.append `calls with a list of different `Operations` added to the circuit. However, the argument where we have supplied a list can also take more than just list values. For instance:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kmt8hAfZAwDA",
        "colab_type": "code",
        "outputId": "ea0930b7-1f8e-4518-d984-94ec4b30061f",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 85
        }
      },
      "source": [
        "def my_layer():\n",
        "    yield CZ(q0, q1)\n",
        "    yield [H(q) for q in (q0, q1, q2)]\n",
        "    yield [CZ(q1, q2)]\n",
        "    yield [H(q0), [CZ(q1, q2)]]\n",
        "\n",
        "circuit = cirq.Circuit()\n",
        "circuit.append(my_layer())\n",
        "\n",
        "for x in my_layer():\n",
        "    print(x)"
      ],
      "execution_count": 31,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "CZ((0, 0), (1, 0))\n",
            "[cirq.H.on(cirq.GridQubit(0, 0)), cirq.H.on(cirq.GridQubit(1, 0)), cirq.H.on(cirq.GridQubit(2, 0))]\n",
            "[cirq.CZ.on(cirq.GridQubit(1, 0), cirq.GridQubit(2, 0))]\n",
            "[cirq.H.on(cirq.GridQubit(0, 0)), [cirq.CZ.on(cirq.GridQubit(1, 0), cirq.GridQubit(2, 0))]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "LXs7ffVWAwDC",
        "colab_type": "code",
        "outputId": "9a55cbd4-abdd-45e6-f2e8-d36d4e282902",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        }
      },
      "source": [
        "print(circuit)"
      ],
      "execution_count": 32,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───@───H───H───────\n",
            "           │\n",
            "(1, 0): ───@───H───@───@───\n",
            "                   │   │\n",
            "(2, 0): ───H───────@───@───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DpGimiozAwDE",
        "colab_type": "text"
      },
      "source": [
        "Recall that Python functions with a `yield` are generators. Generators are functions that act as iterators. In the above example, we see that we can iterate `over my_layer()`. In this case, each of the `yield` returns produces what was yielded, and here these are:\n",
        "\n",
        "* `Operations`, \n",
        "* lists of `Operations`,\n",
        "* or lists of `Operations` mixed with lists of `Operations`. \n",
        "\n",
        "\n",
        "When we pass an iterator to the `append` method, `Circuit` is able to flatten all of these and pass them as one giant list to `Circuit.append` (this also works for `Circuit.insert`).\n",
        "\n",
        "The above idea uses the concept of `OP_TREE`. An `OP_TREE` is not a class, but a *contract*. The basic idea is that, if the input can be iteratively flattened into a list of operations, then the input is an `OP_TREE`.\n",
        "\n",
        "A very nice pattern emerges from this structure: define generators for sub-circuits, which can vary by size or `Operation` parameters.\n",
        "\n",
        "Another useful method to construct a `Circuit` fully formed from an `OP_TREE` is to pass the `OP_TREE` into `Circuit` when initializing it:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "dC6iBIqrAwDF",
        "colab_type": "code",
        "outputId": "d9cd4e3a-997e-4c51-862f-fdf45aef09bf",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 68
        }
      },
      "source": [
        "circuit = cirq.Circuit(H(q0), H(q1))\n",
        "print(circuit)"
      ],
      "execution_count": 33,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───H───\n",
            "\n",
            "(1, 0): ───H───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dE0kxo6tAwDI",
        "colab_type": "text"
      },
      "source": [
        "### Slicing and Iterating over Circuits\n",
        "\n",
        "Circuits can be iterated over and sliced. When they are iterated, each item in the iteration is a moment:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "z2csEbbyAwDI",
        "colab_type": "code",
        "outputId": "a06555c1-2e28-4ad5-8f26-427275f65fb1",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 51
        }
      },
      "source": [
        "circuit = cirq.Circuit(H(q0), CZ(q0, q1))\n",
        "for moment in circuit:\n",
        "    print(moment)"
      ],
      "execution_count": 34,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "H((0, 0))\n",
            "CZ((0, 0), (1, 0))\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8gT1t2drAwDL",
        "colab_type": "text"
      },
      "source": [
        "Slicing a `Circuit`, on the other hand, produces a new `Circuit` with only the moments corresponding to the slice:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "hxczWjkMAwDL",
        "colab_type": "code",
        "outputId": "0961ac40-2cf6-4897-c18b-1f8397a544a5",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 68
        }
      },
      "source": [
        "circuit = cirq.Circuit(H(q0), CZ(q0, q1), H(q1), CZ(q0, q1))\n",
        "print(circuit[1:3])"
      ],
      "execution_count": 35,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───@───────\n",
            "           │\n",
            "(1, 0): ───@───H───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cDAVDT7bAwDO",
        "colab_type": "text"
      },
      "source": [
        "Especially useful is dropping the last moment (which are often just measurements): `circuit[:-1]`, or reversing a circuit: `circuit[::-1]`.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ecsv-L6G0Xdg",
        "colab_type": "text"
      },
      "source": [
        "## Circuit Optimizers\n",
        "\n",
        "Cirq comes with the concept of an optimizer.  Optimizers will pass over a circuit and perform tasks that will modify the circuit in place.  These can be used to transform a circuit in specific ways, such as combining single-qubit gates, commuting Z gates through the circuit, or readying the circuit for certain hardware or gate set configurations.\n",
        "\n",
        "Optimizers will have a function `optimize_circuit()` that can be used to perform this optimization.  Here is a simple example that removes empty moments:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "3CLZIOfaH8TU",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 51
        },
        "outputId": "d7ee54fc-3cc5-46c7-c4e5-c38da9584d00"
      },
      "source": [
        "c=cirq.Circuit()\n",
        "c.append(cirq.Moment([]))\n",
        "c.append(cirq.Moment([cirq.X(cirq.GridQubit(1,1))]))\n",
        "c.append(cirq.Moment([]))\n",
        "print(f'Before optimization, Circuit has {len(c)} moments')\n",
        "\n",
        "cirq.DropEmptyMoments().optimize_circuit(circuit=c)\n",
        "print(f'After optimization, Circuit has {len(c)} moments')"
      ],
      "execution_count": 36,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Before optimization, Circuit has 3 moments\n",
            "After optimization, Circuit has 1 moments\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xu59JwhGJh3J",
        "colab_type": "text"
      },
      "source": [
        "Optimizers that come with cirq can be found in the `cirq.optimizers` package.\n",
        "\n",
        "A few notable examples are:\n",
        "\n",
        "*   **ConvertToCzAndSingleGates**: Attempts to convert a circuit into CZ gates and single qubit gates.  This uses gate's unitary and decompose methods to transform them into CZ + single qubit gates.\n",
        "*   **DropEmptyMoments** / **DropNegligible**:  Removes moments that are empty or have very small effects, respectively.\n",
        "*   **EjectPhasedPaulis**: Pushes X, Y, and PhasedX gates towards the end of the circuit, potentially absorbing Z gates and modifying gates along the way.\n",
        "*   **EjectZ**:  Pushes Z gates towards the end of the circuit, potentially adjusting phases of gates that they pass through.\n",
        "*   **ExpandComposite**:  Uses `cirq.decompose` to expand composite gates.\n",
        "*   **MergeInteractions**:  Combines series of adjacent one and two-qubit gates acting on a pair of qubits.\n",
        "*   **MergeSingleQubitGates**:  Combines series of adjacent unitary 1-qubit operations\n",
        "*   **SynchronizeTerminalMeasurements**:  Moves all measurements in a circuit to the final moment if possible.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zzweWA5WJykN",
        "colab_type": "text"
      },
      "source": [
        "### Creating your own optimizers\n",
        "\n",
        "You can create your own optimizers to transform and modify circuits to fit hardware, gate sets, or other requirements.  Optimizers can also be used to generate noise.  See [noise](noise.md) for details.\n",
        "\n",
        "You can do this by implementing the function `optimize_circuit`.\n",
        "\n",
        "If your optimizer is a local optimizer and depends primarily on operator being examined, you can alternatively inherit `cirq.PointOptimizer` and implement the function `optimization_at(self, circuit, index, op)` that optimizes a single operation.\n",
        "\n",
        "Below is an example of implementing a simple `PointOptimizer` that removes measurements."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lB__WndjHWGa",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 85
        },
        "outputId": "b8efd719-30b1-4d8f-833e-6d89b305e260"
      },
      "source": [
        "class RemoveMeasurements(cirq.PointOptimizer):\n",
        "    def optimization_at(self, circuit: cirq.Circuit, index: int, op: cirq.Operation):\n",
        "      if isinstance(op.gate, cirq.MeasurementGate):\n",
        "        return cirq.PointOptimizationSummary(clear_span=1,\n",
        "                                             new_operations=[],\n",
        "                                             clear_qubits=op.qubits)\n",
        "      else:\n",
        "        return None\n",
        "\n",
        "q=cirq.LineQubit(0)\n",
        "c=cirq.Circuit(cirq.X(q), cirq.measure(q))\n",
        "print('Before optimization')\n",
        "print(c)\n",
        "RemoveMeasurements().optimize_circuit(c)\n",
        "print('After optimization')\n",
        "print(c)\n"
      ],
      "execution_count": 37,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Before optimization\n",
            "0: ───X───M───\n",
            "After optimization\n",
            "0: ───X───────\n"
          ],
          "name": "stdout"
        }
      ]
    }
  ]
}
